package com.lwc.cfdns.utils.file.upload;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.lwc.cfdns.config.AttachmentAliyunOssConfig;
import com.lwc.cfdns.utils.SpringContextUtils;
import com.lwc.cfdns.utils.file.MimeTypeUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 * 阿里云oss上传
 *
 * @author luwc
 * @title AliyunOssFileUpload
 * @description
 * @time 2023/9/19 10:59:03
 * @version: 1.0
 */
public class AliyunOssFileUpload extends AbstractFileUpload {
    /**
     * 域名或前缀
     *
     * @param
     * @return String
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/9/19 15:14:32
     */
    @Override
    public String getUploadDomain() {
        return AttachmentAliyunOssConfig.getUploadDomain();
    }

    @Override
    public String upload(MultipartFile file, String[] allowedExtension) {
        checkFile(file, allowedExtension);
        // 获取文件原名称
        String originalFilename = file.getOriginalFilename();
        String newPath = createPath();
        // 新文件名称
        String newFileName = createFileName(file);
        // 文件上传的路径地址
        String uploadImgeUrl = "test/" + newPath + "/" + newFileName;
        // 获取文件输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * 下面两行代码是重点坑：
         * 现在阿里云OSS 默认图片上传ContentType是image/jpeg
         * 也就是说，获取图片链接后，图片是下载链接，而并非在线浏览链接，
         * 因此，这里在上传的时候要解决ContentType的问题，将其改为image/jpg
         */
        ObjectMetadata meta = new ObjectMetadata();
        String extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        if (extension != "") {
            meta.setContentType(file.getContentType());
        }
        OSSClient ossClient = (OSSClient) SpringContextUtils.getBean("OSSClient");
        PutObjectResult putObjectResult = ossClient.putObject(AttachmentAliyunOssConfig.getBucketName(), uploadImgeUrl, inputStream, meta);

        return "/" + uploadImgeUrl;
    }
}
